<template>
	<div>
		<el-row style="margin-top: 30px; margin-left: 30px">
			<el-form :inline="true" ref="sel_form">
				<!-- 快捷搜索框 -->
				<el-form-item label="">
					<el-input v-model="search_data" class="input-with-select">
						<el-button slot="append" type="primary" icon="el-icon-search" @click="QueryRootDirectory">搜索</el-button>
					</el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="danger" v-show="isShowButton" @click="caozuoDialog(4, {})">批量删除</el-button>
				</el-form-item>
			</el-form>
			<!-- 删除单个文件/文件夹对话框 -->
			<el-dialog title="删除确认" :visible.sync="DeleteDialog" width="30%">
				<span>确定要删除吗?</span>
				<span slot="footer" class="dialog-footer">
					<el-button @click="DeleteDialog = false">取 消</el-button>
					<el-button type="primary" @click="deleteMethod(currentFileOrFolder)">确 定</el-button>
				</span>
			</el-dialog>
			<!-- 批量删除文件/文件夹对话框 -->
			<el-dialog title="删除确认" :visible.sync="MultipleDeleteDialog" width="30%">
				<span>确定要删除吗?</span>
				<span slot="footer" class="dialog-footer">
					<el-button @click="MultipleDeleteDialog = false">取 消</el-button>
					<el-button type="primary" @click="multipleDelete()">确 定</el-button>
				</span>
			</el-dialog>
			<!-- 文件/文件夹审核对话框 -->
			<el-dialog title="学习资料审核" :visible.sync="RenameDialog" width="30%">
				<el-form :model="currentFileOrFolder" label-width="auto">
					<el-form-item label="审核状态">
						<el-select v-model="currentFileOrFolder.status">
							<el-option value="0" label="待审核" />
							<el-option value="1" label="通过" />
							<el-option value="2" label="不通过" />
						</el-select>
					</el-form-item>
					<el-form-item label="备注">
						<el-input v-model="currentFileOrFolder.remark"></el-input>
					</el-form-item>
				</el-form>
				<span slot="footer" class="dialog-footer">
					<el-button @click="RenameDialog = false">取 消</el-button>
					<el-button type="primary" @click="
              RenameMethod(
                currentFileOrFolder._id,
                currentFileOrFolder.status,
				currentFileOrFolder.remark
              )
            ">确 定</el-button>
				</span>
			</el-dialog>
		</el-row>
		<!-- 面包屑 -->
		<el-row style="margin-left: 30px; margin-top: 10px">
			<el-page-header class="pageHeader" :content="'当前所处：' + currentLocationName" @back="goBack">
			</el-page-header>
		</el-row>
		<!-- 展示根目录表格 -->
		<el-row style="margin-left: 30px; margin-top: 10px">
			<el-table ref="multipleTable" tooltip-effect="dark" @selection-change="handleSelectionChange"
				:data="tableData" style="width: 100%">
				<el-table-column type="selection" style="width: 10%"> </el-table-column>
				<el-table-column label="文件名">
					<template slot-scope="scope">
						<!-- 这里替换为您的图片路径 -->
						<img :src="getFileIcon(scope.row.type)" alt="File Icon"
							style="width: 18px; height: 18px; vertical-align: middle" />
						&nbsp;
						<span @click="RowClick(scope.row)" style="cursor: pointer">{{
              scope.row.fileName
            }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="fileSize" label="大小">
				</el-table-column>
				<el-table-column prop="createDate" label="创建日期">
				</el-table-column>
				<el-table-column prop="status" label="审核状态">
					<template slot-scope="scope">
						<span v-if="scope.row.status == 0">待审核</span>
						<span v-if="scope.row.status == 1">审核通过</span>
						<span v-if="scope.row.status == 2">审核不通过</span>
					</template>
				</el-table-column>
				<el-table-column prop="remark" label="备注">
				</el-table-column>
				<el-table-column label="操作">
					<template slot-scope="scope">
						<el-button v-if="scope.row.type !== 'folder'" @click="SingleDownload(scope.row)" type="text" size="small">下载</el-button>
						<el-button v-if="scope.row.status == '0'" @click="caozuoDialog(2, scope.row)" type="text" size="small">审核</el-button>
						<el-button @click="caozuoDialog(3, scope.row)" type="text" size="small">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-row>
	</div>
</template>

<script>
	import router from "../../router.js";
	import Folder from '../../assets/Folder.png';
	import Audio from '../../assets/Audio.png';
	import Excel from '../../assets/Excel.png';
	import PPT from '../../assets/PPT.png';
	import Package from '../../assets/package.png';
	import PDF from '../../assets/PDF.png';
	import Video from '../../assets/Video.png';
	import Word from '../../assets/Word.png'; 
	import Image from '../../assets/Image.png';
	export default {
		data() {
			return {
				currentLocationName: '根目录',
				currentParentId:"",
				MultipleDeleteDialog: false,
				isShowButton: false,
				isShowButton1: true,
				multipleSelection: [],
				RenameDialog: false,
				search_data: "",
				currentFileOrFolder: {
					_id: "",
					file_id: "",
					status: "",
					remark: "",
					fileName: "",
					createDate: "",
					fileSize: "",
					type: "",
					parentId:"",
				},
				UploadFileDialog: false,
				NewFolderDialog: false,
				DeleteDialog: false,
				tableData: [],
				newFloderform: {
					fileName: "新建文件夹",
					createDate: "",
					fileSize: "--",
					file_id:"",
					status:"0",
					remark:"",
					parentId:"",
					type: "folder",
				},
			};
		},
		// 生命周期函数
		mounted() {
			this.QueryRootDirectory();
		},
		methods: {
			//根据文件类型返回具体图标
			getFileIcon(type){
				switch (type){
					case 'folder':
						return Folder;
					case 'application/msword':
						return Word;
					case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
						return Word;
					case 'application/pdf':
						return PDF;
					case 'application/vnd.openxmlformats-officedocument.presentationml.presentation':
						return PPT;
					case 'application/vnd.ms-powerpoint':
						return PPT;
					case 'application/vnd.ms-excel':
						return Excel;
					case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
						return Excel;
					case 'video/mp4':
						return Video;
					case 'audio/mpeg':
						return Audio;
					case 'image/png':
						return Image;
					case 'image/jpg':
						return Image;
					case 'image/gif':
						return Image;
					case 'application/octet-stream':
						return Package;
				}
			},
			// 批量下载(暂时不好使)
			async multipleDownload() {
				// console.log(this.multipleSelection);
				let file_list = [];
				let file_name = [];
				for (let i = 0; i < this.multipleSelection.length; i++) {
					// console.log(this.multipleSelection[i]);
					if (this.multipleSelection[i].type !== "folder") {
						let obj1 = {};
						obj1.fileid = this.multipleSelection[i].file_id;
						obj1.max_age = 7200;
						file_list.push(obj1);
						let obj2 = {};
						obj2.fileName = this.multipleSelection[i].fileName;
						obj2.fileid = this.multipleSelection[i].file_id;
						obj2.type = this.multipleSelection[i].type;
						file_name.push(obj2);
					}
				}
				const data = {file_list, file_name,};
				fetch("api/multipledownload", {
						method: "POST",
						headers: {
							"Content-Type": "application/json",
						},
						body: JSON.stringify(data),
					})
					.then((response) => response.json())
					.then(async (result) => {
						if (result.status === 1) {
							console.log(result);
							for (let i = 0; i < result.data.length; i++) {
								const blob = new Blob([result.data[i].fileStream], {
									type: "application/octet-stream",
								});
								const link = document.createElement("a");
								const url = URL.createObjectURL(blob);
								link.href = url;
								link.download = result.data[i].fileName;
								document.body.appendChild(link);
								link.click();
								document.body.removeChild(link);
							}
						} else {
							this.$message({
								showClose: true,
								message: "下载失败",
								type: "error",
							});
						}
					})
					.catch((error) => {
						console.log("发生错误", error);
					});
			},
			// 单个下载（所有目录都好使）
			async SingleDownload(row) {
				// 判断文件是否为空或者有子文件夹，如果符合立刻报错中断函数
				if (row.type === "folder") {
					if (row.include.length === 0) {
						this.$message({
							showClose: true,
							message: "空文件夹不能下载",
							type: "error",
						});
						return;
					}
					for (let i = 0; i < row.include.length; i++) {
						if (row.include[i].type === "folder") {
							this.$message({
								showClose: true,
								message: "空文件夹不能下载",
								type: "error",
							});
							return;
						}
					}
				}
				const response = await fetch("api/downloadfileorfolder", {
					method: "post",
					headers: {
						"Content-Type": "application/json",
					},
					body: JSON.stringify({
						file_id: row.file_id,
						fileName: row.fileName,
					}),
				});
				// console.log("1111111111", response);
				if (!response.ok) {
					console.log("下载文件失败");
				} else {
					const blob = await response.blob();
					const link = document.createElement("a");
					link.href = window.URL.createObjectURL(blob);
					link.download = row.fileName;
					link.click();
				}
			},
			// 批量删除（所有目录都好使）
			async multipleDelete() {
				this.MultipleDeleteDialog = false;
				const currentListId = this.currentListId;
				// console.log(this.multipleSelection);
				const multipleSelection = this.multipleSelection;
				const isToRemove = multipleSelection.map(obj=>obj._id);
				const arr = this.tableData.filter(obj=>!isToRemove.includes(obj._id));
				console.log(arr);
				let res = await this.$axios({
					url: "api/multipledelete",
					method: "post",
					data: {
						multipleSelection,
						currentListId,
						arr
					},
				});
				// console.log(res);
				if (res.data.status === 1) {
					this.QueryRootDirectory();
					this.$message({
						showClose: true,
						message: "批量删除成功",
						type: "success",
					});
				} else {
					this.$message({
						showClose: true,
						message: "批量删除失败",
						type: "error",
					});
				}
			},
			// 多选
			handleSelectionChange(val) {
				this.multipleSelection = val;
				if (this.multipleSelection.length !== 0) {
					this.isShowButton = true;
				} else {
					this.isShowButton = false;
				}
			},
			// 文件上传成功后的事件
			handleUploadSuccess(response, file, fileList) {
				// console.log(response);
				if (response.status === 1) {
					this.QueryRootDirectory();
					this.$message({
						showClose: true,
						message: "上传文件成功",
						type: "success",
					});
				} else {
					this.$message({
						showClose: true,
						message: "文件上传失败",
						type: "error",
					});
				}
				this.UploadFileDialog = false;
			},
			// 文件夹点击函数
			RowClick(row) {
				if (row.type === "folder") {
					this.isShowButton1 = false;
					this.currentLocationName += '/' + row.fileName;
					this.currentParentId = row._id;
					this.tableData = [];
					this.QueryRootDirectory();
				}
			},
			// 返回
			goBack() {
				if (this.currentLocationName !== '根目录') {
					this.currentParentId = "";
					this.QueryRootDirectory();
					this.currentLocationName = '根目录';
					this.isShowButton1 = true;
				} else {
					this.$message({
						message: '已经退到根目录了,不能再退了',
						type: 'warning'
					});
				}
			},
			// 展示操作对话框
			caozuoDialog(param, row) {
				// console.log(row);
				for (let i in row) {
					this.currentFileOrFolder[i] = row[i];
				}
				if (param === 1) {
					// console.log("上传文件");
					this.UploadFileDialog = true;
				} else if (param === 2) {
					// console.log("重命名");
					this.RenameDialog = true;
					if (this.currentFileOrFolder.type !== "folder") {
						// 这里调用一个函数处理一下文件名的后缀
						let index = this.currentFileOrFolder.fileName.lastIndexOf(".");
						let name = this.currentFileOrFolder.fileName.slice(0, index);
						let suffix = this.currentFileOrFolder.fileName.slice(
							index,
							this.currentFileOrFolder.fileName.length
						);
						this.currentFileOrFolder.fileName = [name, suffix];
					} else {
						this.currentFileOrFolder.fileName = [
							this.currentFileOrFolder.fileName,
							"",
						];
					}
				} else if (param === 3) {
					// console.log("删除");
					this.DeleteDialog = true;
				} else if (param === 4) {
					// console.log('批量删除');
					this.MultipleDeleteDialog = true;
				} else if (param === 5) {
					// console.log("新建文件夹");
					this.NewFolderDialog = true;
				}
			},
			// 文件/文件夹重命名（所有目录都好使）
			async RenameMethod(_id, status, remark) {
				this.RenameDialog = false;
				let res = await this.$axios({
					url: "/api/auditfileorfolder",
					method: "post",
					data: {_id,status,remark},
					});
				if (res && res.data.status === 1) {
					this.QueryRootDirectory();
					this.$message({
						showClose: true,
						message: "审核成功",
						type: "success",
					});
				} else {
					this.$message({
						showClose: true,
						message: "审核失败",
						type: "error",
					});
				}
			},
			// 单个删除文件/文件夹（所有目录都好使）
			async deleteMethod(currentFileOrFolder) {
				this.DeleteDialog = false;
				let currentListId = this.currentListId;
				// console.log(_id);
				let arr = [];
				for(let i=0;i<this.tableData.length;i++){
					let temp = {};
					for(let j in this.tableData[i]){
						temp[j] = this.tableData[i][j];
					}
					if(temp._id !== currentFileOrFolder._id){
						arr.push(temp);
					}
				}
				let res = await this.$axios({
					url: "api/deletefileorfolder",
					method: "post",
					data: {
						currentFileOrFolder,
						currentListId,
						arr
					},
				});
				// console.log(res);
				if (res && res.data.status === 1) {
					this.QueryRootDirectory();
					this.$message({
						showClose: true,
						message: "恭喜你，删除成功",
						type: "success",
					});
				} else {
					this.$message({
						showClose: true,
						message: "删除失败",
						type: "error",
					});
				}
			},
			// 查询文件列表
			async QueryRootDirectory() {
				this.tableData = [];
				let res = await this.$axios({
					url: "/api/rootdirectory",
					method: "post",
					data:{parentId:this.currentParentId,fileName:this.search_data}
				});
				// console.log(res);
				for (let i = 0; i < res.data.data.length; i++) {
					let temp = JSON.parse(res.data.data[i]);
					this.tableData.push(temp);
				}
				// console.log(this.tableData)
			},
			// 新建文件夹
			async newFolder(paths) {
				this.NewFolderDialog = false;
				console.log("222222", paths);
				let form = this.newFloderform;
				if (form.fileName === "") {
					this.$message({
						showClose: true,
						message: "添加失败，请检查是否有空信息",
						type: "error",
					});
				} else {
					let temp = form.fileName;
					let num = 1;
					while (true) {
						if (this.checkfileName(temp)) {
							temp = form.fileName + `(${num})`;
							num++;
						} else {
							form.fileName = temp;
							break;
						}
					}
					// 处理文件夹创建时间
					form.createDate = this.formatDate();
					// console.log("1111111111111", form);
					let res = await this.$axios({
						url: "api/createnewfolder",
						method: "post",
						data: {
							form,
						},
					});
					// console.log(res);
					if (res && res.data.status === 1) {
						this.QueryRootDirectory();
						this.$message({
							showClose: true,
							message: "恭喜你，添加成功",
							type: "success",
						});
					} else {
						this.$message({
							showClose: true,
							message: "添加失败，请检查是否有空信息",
							type: "error",
						});
					}
				}

				this.newFloderform = {
					fileName: "新建文件夹",
					createDate: "",
					fileSize: "--",
					include: [],
					fileId: "cloud://cloud1-4gfhls3pb83e8f3c.636c-cloud1-4gfhls3pb83e8f3c-1325827386/文件类型素材/Folder.png",
					type: "folder",
				};
			},
			// 检查文件名是否有重复
			checkfileName(fileName) {
				for (let i = 0; i < this.tableData.length; i++) {
					if (this.tableData[i].fileName === fileName) {
						return true;
					}
				}
				return false;
			},
			// 处理时间函数
			formatDate() {
				const now = new Date();
				// 获取当前年份、月份（注意月份是从0开始的，所以要+1）、日期
				const year = now.getFullYear();
				const month = String(now.getMonth() + 1).padStart(2, "0");
				const date = String(now.getDate()).padStart(2, "0");
				const hours = String(now.getHours()).padStart(2, "0"); // 小时（24小时制）
				const minutes = String(now.getMinutes()).padStart(2, "0"); // 分钟

				// 拼接字符串
				return `${year}-${month}-${date} ${hours}:${minutes}`;
			},
		},
	};
</script>

<style>
	.el-icon-arrow-left:hover {
		color: #409eff;
	}
</style>